package com.ruoyi.project.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.project.domain.ProjectTemplate;
import com.ruoyi.project.mapper.ProjectTemplateMapper;
import com.ruoyi.project.service.ProjectTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;


@Service
@Slf4j
public class ProjectTemplateServiceImpl extends ServiceImpl<ProjectTemplateMapper, ProjectTemplate> implements ProjectTemplateService {

    @Override
    public ProjectTemplate getTree() {
        //获取根目录
        LambdaQueryWrapper<ProjectTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(ProjectTemplate::getParentId);
        ProjectTemplate projectTemplate = this.baseMapper.selectOne(queryWrapper);
        if(Objects.nonNull(projectTemplate)){
            getChildren(projectTemplate);
             return projectTemplate;
        }
        return null;
    }

    private void getChildren(ProjectTemplate projectTemplate){
        LambdaQueryWrapper<ProjectTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectTemplate::getParentId,projectTemplate.getId());
        List<ProjectTemplate> projectTemplates = this.baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(projectTemplates)){
           for (ProjectTemplate projectTemplate1 : projectTemplates) {
                getChildren(projectTemplate1);
            }
        }
        projectTemplate.setChildren(projectTemplates);
    }


}